using System;
using System.Collections.Generic;
using System.Text;
using LeisureCenter.Api;
using System.Windows.Forms;
using System.Configuration;
using FMOD;

namespace FModPlayer
{
    [AudioCdPlayer]
    public class FModPlayer : BasePlayer, IDisposable
    {
        private FMOD.System system;
        public FMOD.System FModSystem { get { return system; } }
        internal Timer updateTimer = new Timer();
        public IInstance leisureCenterInstance;

        public const string Name = "FMod";

        public FModPlayer(IInstance leisureCenterInstance)
        {
            this.leisureCenterInstance = leisureCenterInstance;

            FModSettings settings = new FModSettings();

            FMOD.Factory.System_Create(ref system);

            system.setSoftwareFormat(48000, SOUND_FORMAT.PCM16, 0, 0, DSP_RESAMPLER.LINEAR);
            system.setSpeakerMode(settings.SpeakerMode);
            system.init(3, FMOD.INITFLAG.NORMAL | INITFLAG.DSOUND_HRTFFULL, (IntPtr)null);

            updateTimer.Interval = 1;
            updateTimer.Tick += new EventHandler(updateTimer_Tick);
        }

        void updateTimer_Tick(object sender, EventArgs e)
        {
            try
            {
                system.update();
            }
            catch (AccessViolationException)
            {
                // don't know why it happens why switching to a video, but catching it seems enough
            }
        }

        ~FModPlayer()
        {
            system.close();
            system.release();
        }

        #region IPlayer implementation

        public override IMedia CreateMedia(string fileName, MediaKind kind)
        {
            if (kind == MediaKind.Music)
                return new FModAudioMedia(this, fileName);
            else
            if (kind == MediaKind.CD)
                return new FModAudioCdMedia(this, fileName);
            else
                return null;
        }

        #endregion

        #region IDisposable Membres

        public void Dispose()
        {
            throw new Exception("The method or operation is not implemented.");
        }

        #endregion
    }
}
